from time import strftime, localtime
import string
import random

from gi.repository import Gtk, Gdk

from mylib.timer import ThreadTimer


class CellRendererTextWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="CellRendererText Example")
        geo = Gdk.Geometry()
        geo.min_width = 200
        geo.max_width = 300
        geo.min_height = 300
        geo.max_height = 500
        # self.set_geometry_hints(self, min_width=200, min_height=300, max_width=300, max_height=500)
        # self.set_default_size(200, 200)
        self.set_geometry_hints(None, geo, Gdk.WindowHints.MAX_SIZE | Gdk.WindowHints.MIN_SIZE)
        self.liststore = Gtk.ListStore(str, str)
        self.liststore.append(["Fedora", "http://fedoraproject.org/"])
        self.liststore.append(["Slackware", "http://www.slackware.com/"])
        self.liststore.append(["Sidux", "http://sidux.com/"])

        self.treeview = Gtk.TreeView(model=self.liststore)

        renderer_text = Gtk.CellRendererText()
        column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0)
        self.treeview.append_column(column_text)

        renderer_editable_text = Gtk.CellRendererText()
        renderer_editable_text.set_property("editable", True)

        column_editable_text = Gtk.TreeViewColumn("Editable Text", renderer_editable_text, text=1)
        self.treeview.append_column(column_editable_text)

        renderer_editable_text.connect("edited", self.text_edited)

        scrolled_window = self.create_scrolled_window()
        scrolled_window.add(self.treeview)

        self.add(scrolled_window)

        # self.timer = MyTimer(0.1, self.on_timer)
        # self.timer.start()
        self.timer = ThreadTimer(0.05, self.on_timer)
        self.timer.start()

    def on_timer(self):
        tm = strftime('%Y-%m-%d %T >', localtime())
        line = ''.join(random.choice(string.ascii_lowercase) for _ in range(11))
        self.liststore.append([tm, line])
        model = self.treeview.get_model()
        while len(self.liststore) > 10:
            first_iter = model.get_iter_first()
            if self.liststore.iter_is_valid(first_iter):
                self.liststore.remove(first_iter)

    def create_scrolled_window(self):
        scrolled_window = Gtk.ScrolledWindow(hadjustment=None, vadjustment=None)
        scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        scrolled_window.set_shadow_type(Gtk.ShadowType.IN)
        return scrolled_window

    def text_edited(self, widget, path, text):
        print(type(widget))
        self.liststore[path][1] = text


win = CellRendererTextWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()